package mjc.compiler;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class TDS extends HashMap<String, INFO> implements Serializable {

	private static final long serialVersionUID = 1L;

	private TDS parente;

	public TDS () {
		this(null);
	}

	public TDS (TDS p) {
		super();
		parente = p;
	}

	public INFO chercherLocalement(String n) {
		return get(n);
	}

	public INFO chercherGlobalement(String n) {
		INFO i = chercherLocalement(n);
		if (i == null)
			if (parente != null)
				return parente.chercherGlobalement(n);
		return i;
	}

	public void inserer(String n, INFO i) {
		put(n, i);
	}
	
	public void importer(String nom) {
		INFOCLASSE i = null;
		try {
			FileInputStream f = new FileInputStream(nom+".mclass");
			ObjectInputStream s = new ObjectInputStream(f);
			i = (INFOCLASSE) s.readObject();
			f.close();
			inserer(nom, i);
		} catch (FileNotFoundException e) {
			System.out.println("// Compilation de "+nom+".mj nécessaire, exécution.");
			MJC2.compiler(nom+".mj");
			importer(nom);
		} catch (IOException e) {
			System.out.println("Problème lors de l'importation de "+nom+".mclass");
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			System.out.println("Problème lors de l'importation de "+nom+".mclass");
			e.printStackTrace();
		}
	}
	

	public String toString() {
		StringBuffer sb = new StringBuffer();
		Set<Map.Entry<String, INFO>> s = entrySet();
		for (Map.Entry<String, INFO> e : s){
			sb.append("; " + e.getKey() + " : " + e.getValue() + '\n');
		
		}
		return sb.toString();
	}

	public void addVarsFromParams(PARAMETRES p) {
		ArrayList<Couple<String, DTYPE>> params = p.getParams();
		Iterator<Couple<String, DTYPE>> i = params.iterator();
		while(i.hasNext()) {
			Couple<String, DTYPE> c = i.next();
			inserer(c.fst, new INFOATTRIBUT(c.fst, c.snd));
		}
	}
}
